import React, {Component} from 'react';
import {View, StyleSheet, Text, ListView, TouchableOpacity,RefreshControl, Platform,Image,ActivityIndicator} from  'react-native';
import Mock from 'mockjs';
import Icon from 'react-native-vector-icons/FontAwesome';
import {LineDotsLoader} from 'react-native-indicator';
let GeustYouLike = require('../../Data/HomeGeustYouLike.json');
let icon_shop_local = require('../../img/icon_shop_local.png');
let icon_shop_search = require('../../img/icon_shop_search.png');
let dimension = require('Dimensions');
let {width, height} = dimension.get('window');
import BaiduMap from './BaiduMapView';
let cachedResult={
    nextPage:1,
    items:[],
    total:0
};
export default class Shop extends Component {
    constructor(props) {
        super(props);
        this.state={
            dataSource: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),
            isLoadingData:false,
            isRefreshing:false
        };
        this.loadDataFormNet=this.loadDataFormNet.bind(this);
        this.hasMore=this.hasMore.bind(this);
        this.fetchMoreData=this.fetchMoreData.bind(this);
        this._onRefresh=this._onRefresh.bind(this);
        this.renderFooter=this.renderFooter.bind(this);
    }
    render() {
        return (
            <View style={styles.container}>
                {this.renderNavBar()}
                <ListView

                    dataSource={this.state.dataSource}
                    renderRow={this.renderRow}
                    onEndReached={this.fetchMoreData}
                    onEndReachedThreshold={20}
                    renderFooter={this.renderFooter}
                    enableEmptySections={true}
                    showsVerticalScrollIndicator={false}
                    automaticallyAdjustContentInsets={false}
                    removeClippedSubviews={true}
                    refreshControl={
                        <RefreshControl
                        refreshing={this.state.isRefreshing}
                        onRefresh={this._onRefresh}
                        tintColor="#ff0000"
                        title="正在加载数据"
                        titleColor="#00ff00"
                        colors={['#ff0000', '#00ff00', '#0000ff']}
                        progressBackgroundColor="#ffff00"

                        />
                    }
                />
            </View>
        )
    }
    renderRow(rowData) {
        return (
            <TouchableOpacity onPress={()=>{alert("asd")}}>
                <View style={styles.listViewStyle}>
                    <Image source={{uri:rowData.imageurl}} style={styles.imageStyle}/>
                    <View style={styles.rightViewStyle}>
                        <View style={styles.rightTopViewStyle}>
                            <Text>{rowData.title}</Text>
                            <Text>{rowData.distance}</Text>
                        </View>
                        <Text style={{color:'gray'}}>{rowData.address}</Text>
                        <View style={styles.rightBottomViewStyle}>
                            <Text style={{color:'red'}}>{rowData.shopinfo}</Text>
                        </View>
                    </View>
                </View>
            </TouchableOpacity>
        )
    }
    componentDidMount() {
        this.loadDataFormNet(1);
    }
    loadDataFormNet(page) {
        let that=this;
        if (page!==0) {
            that.setState({
                isLoadingData: true
            });
        }
        else {
            that.setState({
                isRefreshing: true
            });
        }
        setTimeout(()=>{
        fetch(this.props.api_url)
            .then((response) => response.json())
            .then((responseData) => {
            let data =Mock.mock(responseData);
            if (data.success) {
                let items=cachedResult.items.slice();
                if (page!==0) {
                    items = items.concat(data.data);
                    cachedResult.nextPage+=1;
                }
                else {
                    items=data.data.concat(items)
                }

                cachedResult.items=items;
                cachedResult.total=data.total;
                // setTimeout(function () {
                    if (page!==0) {
                        that.setState({
                            isLoadingData: false,
                            dataSource: that.state.dataSource.cloneWithRows(cachedResult.items)
                        })
                    }
                    else {
                        that.setState({
                            isRefreshing: false,
                            dataSource: that.state.dataSource.cloneWithRows(cachedResult.items)
                        })
                    }
                // },2000)

            }
            })
            .catch((error) => {
                if (page!==0) {
                    this.setState({
                        isLoadingData: false,
                    })
                }
                else {
                    this.setState({
                        isRefreshing: false,
                    })
                }
            })},5000);
    }
    //如果需要右边添加图标，则设置为leftViewStyle
    renderNavBar() {
        return (
            <View style={styles.navOutViewStyle}>

                <Text style={{color:'white', fontSize:16, fontWeight:'bold'}}>商家</Text>

                <TouchableOpacity onPress={()=>{this.openMap()}} style={styles.rightViewStyle1}>
                    <Icon name="map-pin" size={16} color="white"/>
                </TouchableOpacity>
            </View>
        )
    }
// <Image source={icon_shop_local} style={styles.navImageStyle}/>
    openMap(){
        const { navigate } = this.props.navigation;
        navigate('BaiduMapView');
        // const {navigator} = this.props;
        // if (navigator) {
        //     navigator.push({
        //         component: BaiduMap,
        //         name: 'BaiduMap',
        //         params: {
        //             // tabBar: {
        //             //     hide: () => this.props.tabBar.hide(),
        //             //     show: () => this.props.tabBar.show()
        //             // }
        //         }
        //     })
        // }
    }
    hasMore(){
        return cachedResult.items.length!==cachedResult.total;
    }
    fetchMoreData(){
        if (!this.hasMore()||this.state.isLoadingData){
            return;
        }
        let page=cachedResult.nextPage;
        this.loadDataFormNet(page)
    }
    _onRefresh(){
        if(!this.hasMore()||this.state.isRefreshing){
            return;
        }
        this.setState({
            isRefreshing:true
        });
        this.loadDataFormNet(0)
    }
    renderFooter(){
        if (!this.hasMore()&&cachedResult.total!==0){
            return (
                <View style={styles.loadingMoreStyle}>
                    <Text style={styles.loadingTextStyle}>没有更多了</Text>
                </View>
            )
        }
        return(
            <View style={{marginTop:20,marginBottom:20}}>
                <LineDotsLoader/>
            </View>
        )
    }
}
Shop.propTypes = {
    api_url: React.PropTypes.string
};
Shop.defaultProps = {
    api_url: 'http://rapapi.org/mockjs/18259/api/getShop?accessTocken=aa'
};
const styles = StyleSheet.create({
    container: {
        marginBottom:49
    },
    imageStyle: {
        width: 120,
        height: 90
    },
    listViewStyle: {
        backgroundColor: 'white',
        padding: 10,
        borderBottomColor: '#e8e8e8',
        borderBottomWidth: 0.5,
        flexDirection: 'row',
        overflow:'hidden'
        // justifyContent:'space-between'
    },
    rightViewStyle: {
        marginLeft: 8,
        width: width-10-8-120,
        justifyContent: 'center'
    },
    rightTopViewStyle: {
        flexDirection: 'row',
        marginBottom: 7,
        justifyContent: 'space-between'
    },
    rightBottomViewStyle: {
        flexDirection: 'row',
        marginBottom: 7,
        justifyContent: 'space-between'
    },
    navImageStyle: {
        width: Platform.OS == 'ios' ? 28 : 24,
        height: Platform.OS == 'ios' ? 28 : 24,
    },

    leftViewStyle: {
        // 绝对定位
        position: 'absolute',
        left: 10,
        bottom: Platform.OS == 'ios' ? 15 : 13
    },

    rightViewStyle1: {
        // 绝对定位
        position: 'absolute',
        right: 10,
        bottom: Platform.OS == 'ios' ? 15 : 13
    },

    navOutViewStyle: {
        height: Platform.OS == 'ios' ? 64 : 44,
        backgroundColor: 'rgba(255,96,0,1.0)',

        // 设置主轴的方向
        flexDirection: 'row',
        // 垂直居中 ---> 设置侧轴的对齐方式
        alignItems: 'center',
        // 主轴方向居中
        justifyContent: 'center'
    },
    loadingMoreStyle:{
        marginVertical:8
    },
    loadingTextStyle:{
        color:'#777',
        textAlign:'center'
    }
});

